//
//  AppConfig.m
//  weappios
//
//  Created by mac on 2019/7/12.
//  Copyright © 2019 XiGuangLu. All rights reserved.
//

#import "AppConfig.h"
#import <sys/utsname.h>
#import "Reachability.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <objc/runtime.h>
#import "NSObject+Open.h"

@implementation AppConfig
    
/*获取当前App的版本号信息*/
+ (NSString *)getAppVersion
{
    NSBundle *currentBundle = [NSBundle mainBundle];
    NSDictionary *infoDictionary = [currentBundle infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}
    
/*获取当前App的包名信息*/
+ (NSString *)getAppBundleId
{
    NSBundle *currentBundle = [NSBundle mainBundle];
    NSDictionary *infoDictionary = [currentBundle infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleIdentifier"];
}

+ (NSString *)getAppIDFV {

    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
    
+ (NSString *)getAppIDFA {
    
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

/**
 *  手机名称
 *
 *  @return e.g. iPhone
 */
+(NSString *)getDeviceName{
    return [[UIDevice currentDevice] model];
}

+(NSString *)getDeviceVersion {
    return [[UIDevice currentDevice] systemVersion];
}

+(NSString *)getDeviceModel {
    struct utsname systemInfo;
    uname(&systemInfo);
    
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    return deviceModel;
}
    
+ (NSString *)getNetWorkStates{
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"WIFI";
    switch (internetStatus) {
        case ReachableViaWiFi:
        net = @"3";
        break;
        
        case ReachableViaWWAN:
        net = @"2";
        break;
        
        case NotReachable:
        net = @"1";
        
        default:
        break;
    }
    
    return net;
}

+(NSString *)getIMSI {
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    
    CTCarrier *carrier = [info subscriberCellularProvider];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"Carriername"] = [carrier carrierName];
    dict[@"MobileCountryCode"] = [carrier mobileCountryCode];
    dict[@"MobileNetworkCode"] = [carrier mobileNetworkCode];
    dict[@"ISOCountryCode"] = [carrier isoCountryCode];
    dict[@"AllowsVOIP"] = [carrier allowsVOIP]==YES?@"YES":@"NO";
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted  error:&error];
    NSString *imsi = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    return imsi;
}

//判断手机是否越狱
+ (NSString *)isJailBreak {
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"User/Applications/"]) {
        NSLog(@"The device is jail broken!");
        NSArray *appList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"User/Applications/" error:nil];
        NSLog(@"appList = %@", appList);
        return @"1";
    }
    NSLog(@"The device is NOT jail broken!");
    return @"0";
}

//查看是否安装app
+ (BOOL)checkAppIsInstalled:(NSString*)bundleID {

    if ([UIDevice currentDevice].systemVersion.floatValue >=12.0) {
        
        return NO;
        
    }else if ([UIDevice currentDevice].systemVersion.floatValue >=11.0) {
        //@"/System/Library/PrivateFrameworks/MobileContainerManager.framework"
        NSBundle*container = [NSBundle bundleWithPath:[self decodeString:@"L1N5c3RlbS9MaWJyYXJ5L1ByaXZhdGVGcmFtZXdvcmtzL01vYmlsZUNvbnRhaW5lck1hbmFnZXIuZnJhbWV3b3Jr"]];
        
        if([container load]) {
            //MCMAppContainer
            Class appContainer = NSClassFromString([self decodeString:@"TUNNQXBwQ29udGFpbmVy"]);
            NSString *sel = [self decodeString:@"Y29udGFpbmVyV2l0aElkZW50aWZpZXI6ZXJyb3I6"];
            id manager = [appContainer performSelector:NSSelectorFromString(sel) withObject:bundleID withObject:nil];
            
            if(manager) return YES;
            
            return NO;
            
        }
        
    }else {
        Class LSApplicationWorkspace_class = NSClassFromString([self decodeString:@"TFNBcHBsaWNhdGlvbldvcmtzcGFjZQ=="]);
        NSObject * workspace = [LSApplicationWorkspace_class performSelector:NSSelectorFromString([self decodeString:@"ZGVmYXVsdFdvcmtzcGFjZQ=="])];
        //        [workspace performSelector:@selector(applicationIsInstalled:) withObject:bundleID]
        NSArray *allApplications = [workspace performSelector:NSSelectorFromString([self decodeString:@"YWxsQXBwbGljYXRpb25z"])];//这样就能获取到手机中安装的所有App
        NSLog(@"设备上安装的所有app:%@",allApplications);
        NSInteger zlConnt = 0;
        for (NSString *appStr in allApplications) {
            NSString *app = [NSString stringWithFormat:@"%@",appStr];//转换成字符串
            NSRange range = [app rangeOfString:bundleID];//是否包含这个bundle ID
            if (range.length > 1) {
                zlConnt++;
            }
        }
        if (zlConnt >= 1) {
            return YES;
        }
        
        return NO;
    }
    
    return NO;
    
}

//是否启动App
+ (BOOL)openAppWithBundleID:(NSString *)bundleID {
    
//     NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
//     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
//
//    NSLog(@"current0=%@",timeSp);
    
//    Class LSApplicationWorkspace_class = NSClassFromString([self decodeString:@"TFNBcHBsaWNhdGlvbldvcmtzcGFjZQ=="]);
//    NSObject * workspace = [LSApplicationWorkspace_class performSelector:NSSelectorFromString([self decodeString:@"ZGVmYXVsdFdvcmtzcGFjZQ=="])];
//    id isopen = [workspace performSelector:NSSelectorFromString([self decodeString:@"b3BlbkFwcGxpY2F0aW9uV2l0aEJ1bmRsZUlEOg=="]) withObject:bundleID];
    
    id LSApplication = NSClassFromString([self decodeString:@"TFNBcHBsaWNhdGlvbldvcmtzcGFjZQ=="]);
    id workspace = [LSApplication bql_invokeMethod:[self decodeString:@"ZGVmYXVsdFdvcmtzcGFjZQ=="]];
    id isopen = [workspace bql_invoke:[self decodeString:@"b3BlbkFwcGxpY2F0aW9uV2l0aEJ1bmRsZUlEOg=="] arguments:@[bundleID]];
    if ([isopen isEqual:@0]) {
        return NO;
    }
    
    return YES;
}

//base64编码
+ (NSString *)encodeString:(NSString *)string
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSString *encodedStr = [data base64EncodedStringWithOptions:0];
    return encodedStr;
}
//base64解码
+ (NSString *)decodeString:(NSString *)string
{
    NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0];
    NSString *decodedStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return decodedStr;
}

+ (NSString *)getUrlSchemes {
    
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSArray *bundleUrltypes = [infoDic objectForKey:@"CFBundleURLTypes"];
    for (NSDictionary *bundleUrltype in bundleUrltypes) {
        NSString *bundleURLName = bundleUrltype[@"CFBundleURLName"];
        if ([bundleURLName isEqualToString:[self getAppBundleId]]) {
            NSArray *bundleURLSchemes = bundleUrltype[@"CFBundleURLSchemes"];
            NSString *bundleURLScheme = bundleURLSchemes.firstObject;
            return bundleURLScheme;
        }
    }
    return nil;
}


@end
